package com.runvp.core.interceptor;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.runvp.common.core.redis.RedisCache;
import com.runvp.common.model.auth.BizUserBO;
import com.runvp.common.model.auth.LoginUser;
import com.runvp.common.util.auth.CacheConstants;
import com.runvp.common.util.auth.PlatConstant;
import com.runvp.common.util.auth.RequestHeaderContext;
import com.runvp.common.util.auth.SecurityUtils;
import com.runvp.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {



    @Resource(name = "stringRedisTemplate")
    private ValueOperations<String, String> sops;

    @Autowired
    private RedisCache redisService;

    /**
     * 预处理回调方法，实现处理器的预处理
     * 返回值：true表示继续流程；false表示流程中断，不会继续调用其他的拦截器或处理器
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        long st = System.currentTimeMillis();
        log.info(request.getMethod());
        log.info("=============开始校验token【{}】============",request.getRequestURL());
        String token = getToken(request);
        if (StringUtils.isBlank(token)) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("code", 999);
            map.put("msg", "认证失败");
            outPrintMsg(response, map);
            log.info("=============校验结果：用户未登录，需重新认证============");
            return false;
        }
        String tokenKey = SecurityUtils.buildToken(token);
        String userStr = sops.get(tokenKey);
        if (StringUtils.isNull(userStr)) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("code", 999);
            map.put("msg", "授权失败");
            outPrintMsg(response, map);
            log.info("=============校验结果：token失效，需重新认证,校验用时：【{}】============", (System.currentTimeMillis() - st) + " ms");
            return false;
        }
        LoginUser user = JSONObject.parseObject(userStr,LoginUser.class);
        Long userid = user.getUserId();
        BizUserBO userBO = user.getUserBO();
        String username = userBO.getOpenId();
        if (null == userid) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("code", 999);
            map.put("msg", "授权失败");
            outPrintMsg(response, map);
            log.info("=============校验结果：token失效，需重新认证,校验用时：【{}】============", (System.currentTimeMillis() - st) + " ms");
            return false;
        }
        log.info("【{}】令牌验证通过", username);
        // 设置过期时间
        redisService.expire(tokenKey, PlatConstant.TOKEN_EXPIRE_TIME);
        new RequestHeaderContext.RequestHeaderContextBuild()
                .userId(userid)
                .setUserBO(userBO)
                .build();
        log.info("=============【" + username + "】校验结果：token校验通过,用时：【{}】============", (System.currentTimeMillis() - st) + " ms");
        return true;
    }


    /**
     * 获取请求token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(CacheConstants.HEADER);
        if (StringUtils.isNotEmpty(token) && token.startsWith(CacheConstants.TOKEN_PREFIX)) {
            token = token.replace(CacheConstants.TOKEN_PREFIX, "");
        }
        return token;
    }


    /**
     * 输出提示
     *
     * @param response
     * @param map
     */
    private void outPrintMsg(HttpServletResponse response, Map<String, Object> map) {
        response.setContentType("text/json");
        response.setCharacterEncoding("UTF-8");
        try (PrintWriter out = response.getWriter()) {
            out.print(JSONObject.toJSON(map));
            out.flush();
            out.close();
        } catch (IOException e) {
            log.error("outPrintMsg error :{}", e);
        }
    }

    /**
     * 后处理回调方法，实现处理器（controller）的后处理，但在渲染视图之前
     * 此时我们可以通过modelAndView对模型数据进行处理或对视图进行处理
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        RequestHeaderContext.clean();
    }

    /**
     * 整个请求处理完毕回调方法，即在视图渲染完毕时回调，
     * 如性能监控中我们可以在此记录结束时间并输出消耗时间，
     * 还可以进行一些资源清理，类似于try-catch-finally中的finally，
     * 但仅调用处理器执行链中
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }

}